import React, { useImperativeHandle, useRef, useState } from "react";

interface ChildRef {
  count: number;
  addCount: () => void;
  subCount: () => void;
}
// 18版本
// const Child = React.forwardRef<ChildRef>((props, ref) => {

//   const [count,setCount] = useState(0)

//   useImperativeHandle(ref, () => {
//     return {
//       count,
//       addCount: () => setCount(count + 1),
//       subCount: () => setCount(count - 1),
//     }
//   })
//   return (
//     <div ref={ref}>
//       子组件
//       <div>{ count }</div>
//     </div>
//   )
// })

// 19版本
const Child = ({ref}:{ref:React.RefObject<ChildRef>}) => {

  const [count,setCount] = useState(0)

  // 执行时机和useEffect类似
  // useImperativeHandle(ref, () => {
  //   return {

  //   }
  // },[deps])

  useImperativeHandle(ref, () => {
    return {
      count,
      addCount: () => setCount(count + 1),
      subCount: () => setCount(count - 1),
    }
  })
  return (
    <div ref={ref}>
      子组件
      <div>{ count }</div>
    </div>
  )
}


export default function ImperativeHandle () {

  const childRef = useRef<ChildRef>(null)

  const getChildRef = () => {
    console.log(childRef.current);
  }

  return (
    <>
      <h1>useImperativeHandle</h1>
      <button onClick={getChildRef}>获取子组件</button>
      <button onClick={() => childRef.current?.addCount()}>操作子组件 + 1</button>
      <button onClick={() => childRef.current?.subCount()}>操作子组件 - 1</button>
      <hr />
      <Child ref={childRef}></Child>
    </>
  )
}